#include "camerawidget.h"

CameraWidget::CameraWidget(QWidget *parent) : QWidget(parent) {
    m_layout = new QVBoxLayout(this);
    m_videoWidget = new QVideoWidget(this);
    m_layout->addWidget(m_videoWidget);

    m_camera = nullptr;
    m_captureSession = new QMediaCaptureSession(this);
    m_captureSession->setVideoOutput(m_videoWidget);
}

CameraWidget::~CameraWidget() {
    stopCamera();
}

void CameraWidget::setCamera(const QString &cameraDevice) {
    if (m_camera) {
        delete m_camera;
    }

    if (cameraDevice.isEmpty()) {
        m_camera = new QCamera(this);
    } else {
        // 枚举可用相机设备
        const QList<QCameraDevice> cameras = QMediaDevices::videoInputs();
        if (!cameras.isEmpty()) {
            m_camera = new QCamera(cameras.at(0), this); // 使用第一个相机
        } else {
            qDebug() << "Error: No camera devices found!";
            m_camera = new QCamera(this); // 使用默认相机
        }
    }

    m_captureSession->setCamera(m_camera);
}

void CameraWidget::startCamera() {
    if (m_camera) {
        m_camera->start();
    }
}

void CameraWidget::stopCamera() {
    if (m_camera) {
        m_camera->stop();
    }
}
